<template>
  <div class="user-management" v-loading="loading">
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd">新增用户</el-button>
      <el-input
        v-model="searchKeyword"
        placeholder="请输入用户名、真实姓名或邮箱"
        clearable
        style="width: 300px; margin-left: 16px"
        @keyup.enter="handleSearch" />
      <el-button type="primary" @click="handleSearch" style="margin-left: 8px">搜索</el-button>
    </div>

    <el-table :data="userList" style="width: 100%; margin-top: 20px">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="realName" label="真实姓名" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="roleName" label="角色">
        <template #default="{ row }">
          <el-tag :type="getRoleTagType(row.roleName)">
            {{ row.roleName || "未分配" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? "启用" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180" />
      <el-table-column label="操作" width="280">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="warning" size="small" @click="handleToggleStatus(row)">
            {{ row.status === 1 ? "禁用" : "启用" }}
          </el-button>
          <el-button type="info" size="small" @click="handleResetPassword(row)">重置密码</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="pagination"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      layout="total, prev, pager, next, jumper"
      @current-change="handlePageChange" />

    <!-- 用户表单对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px">
      <el-form :model="userForm" :rules="userFormRules" ref="userFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="userForm.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userForm.realName" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="userForm.roleId" style="width: 100%" placeholder="请选择角色">
            <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="userForm.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog title="重置密码" v-model="passwordDialogVisible" width="400px">
      <el-form :model="passwordForm" :rules="passwordFormRules" ref="passwordFormRef" label-width="100px">
        <el-form-item label="新密码" prop="password">
          <el-input v-model="passwordForm.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleResetPasswordSubmit" :loading="passwordSubmitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { http } from "@/api";

// 表格数据
const userList = ref([]);
const roleList = ref([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 搜索关键词
const searchKeyword = ref("");

// 加载状态
const loading = ref(false);
const submitLoading = ref(false);
const passwordSubmitLoading = ref(false);

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref("新增用户");
const isEdit = ref(false);
const userFormRef = ref(null);

const userForm = reactive({
  id: null,
  username: "",
  password: "",
  realName: "",
  email: "",
  phone: "",
  roleId: null,
  status: 1,
});

// 重置密码对话框
const passwordDialogVisible = ref(false);
const passwordFormRef = ref(null);
const currentUserId = ref(null);

const passwordForm = reactive({
  password: "",
  confirmPassword: "",
});

// 表单验证规则
const userFormRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "用户名长度在 3 到 20 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于 6 个字符", trigger: "blur" },
  ],
  realName: [{ required: true, message: "请输入真实姓名", trigger: "blur" }],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
  ],
  roleId: [{ required: true, message: "请选择角色", trigger: "change" }],
};

const passwordFormRules = {
  password: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于 6 个字符", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.password) {
          callback(new Error("两次输入密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

// 获取用户数据
const fetchUserList = async (page = 1) => {
  loading.value = true;
  try {
    const params = {
      page: page,
      size: pageSize.value,
    };
    if (searchKeyword.value.trim()) {
      params.keyword = searchKeyword.value.trim();
    }
    const res = await http.get("/api/users", params);
    console.log("用户数据:", res.data);
    userList.value = res.data.list;
    total.value = res.data.total;
  } catch (error) {
    ElMessage.error("获取用户列表失败");
    console.error("获取用户列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// 获取角色列表
const fetchRoleList = async () => {
  try {
    const res = await http.get("/api/roles/all");
    roleList.value = res.data;
  } catch (error) {
    console.error("获取角色列表失败:", error);
  }
};

// 获取角色标签类型
const getRoleTagType = (roleName) => {
  const roleMap = {
    超级管理员: "danger",
    管理员: "warning",
    普通用户: "info",
    供应商管理员: "success",
    采购商管理员: "primary",
  };
  return roleMap[roleName] || "info";
};

onMounted(() => {
  fetchUserList(currentPage.value);
  fetchRoleList();
});

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchUserList(page);
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchUserList(1);
};

// 处理新增用户
const handleAdd = () => {
  dialogTitle.value = "新增用户";
  isEdit.value = false;
  Object.assign(userForm, {
    id: null,
    username: "",
    password: "",
    realName: "",
    email: "",
    phone: "",
    roleId: null,
    status: 1,
  });
  dialogVisible.value = true;
};

// 处理编辑用户
const handleEdit = (row) => {
  dialogTitle.value = "编辑用户";
  isEdit.value = true;
  Object.assign(userForm, {
    id: row.id,
    username: row.username,
    password: "",
    realName: row.realName || "",
    email: row.email || "",
    phone: row.phone || "",
    roleId: row.roleId,
    status: row.status,
  });
  dialogVisible.value = true;
};

// 处理删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除该用户吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await http.delete(`/api/users/${row.id}`);
      ElMessage.success("删除成功");
      fetchUserList(currentPage.value);
    } catch (error) {
      ElMessage.error("删除失败");
      console.error("删除用户失败:", error);
    }
  });
};

// 处理启用/禁用状态
const handleToggleStatus = (row) => {
  const newStatus = row.status === 1 ? 0 : 1;
  const statusText = newStatus === 1 ? "启用" : "禁用";

  ElMessageBox.confirm(`确定要${statusText}该用户吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await http.patch(`/api/users/${row.id}/status?status=${newStatus}`);
      ElMessage.success(`${statusText}成功`);
      fetchUserList(currentPage.value);
    } catch (error) {
      ElMessage.error("状态更新失败");
      console.error("更新用户状态失败:", error);
    }
  });
};

// 处理重置密码
const handleResetPassword = (row) => {
  currentUserId.value = row.id;
  Object.assign(passwordForm, {
    password: "",
    confirmPassword: "",
  });
  passwordDialogVisible.value = true;
};

// 处理重置密码提交
const handleResetPasswordSubmit = async () => {
  try {
    await passwordFormRef.value.validate();
    passwordSubmitLoading.value = true;

    await http.patch(`/api/users/${currentUserId.value}/password?password=${passwordForm.password}`);
    ElMessage.success("密码重置成功");
    passwordDialogVisible.value = false;
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message);
    } else {
      ElMessage.error("密码重置失败");
    }
    console.error("重置密码失败:", error);
  } finally {
    passwordSubmitLoading.value = false;
  }
};

// 处理表单提交
const handleSubmit = async () => {
  try {
    await userFormRef.value.validate();
    submitLoading.value = true;

    if (isEdit.value) {
      await http.put(`/api/users/${userForm.id}`, userForm);
      ElMessage.success("更新成功");
    } else {
      await http.post("/api/users", userForm);
      ElMessage.success("添加成功");
    }

    dialogVisible.value = false;
    fetchUserList(currentPage.value);
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message);
    } else {
      ElMessage.error("提交失败");
    }
    console.error("提交用户数据失败:", error);
  } finally {
    submitLoading.value = false;
  }
};
</script>

<style scoped>
.user-management {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}

.operation-bar {
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
